import { openLogin } from '@/global/window/widget';
import useUserStore from '@/store/user';
import { convertParamsToFormat } from '@/utils/common/format';
import { message } from 'ant-design-vue';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
import { nanoid } from 'nanoid';
import { userLogout } from '../modules/system/user/utils';
import { requestList } from './utils';
import { getToken } from '@/store/user/utils';

axios.interceptors.request.use(
  (config: AxiosRequestConfig | any) => {
    if (config.headers) {
      /* 格式化日期 */
      if (config.params && config.params.params) {
        config.url = config.url + '?' + convertParamsToFormat(config.params.params);
        delete config.params.params;
      }
      const userStore = useUserStore();
      config.headers.Authorization = `Bearer ${userStore.$state.token}`;
      const controller = new AbortController();
      config.signal = controller.signal;

      requestList.value.push({
        controller,
        path: `${config.url}`,
        id: nanoid(),
      });
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code === 500) {
      message.warn(res.msg || 'System Error');
      throw new Error(res.msg || '系统内部错误');
    } else if (res.code === 403) {
      message.warn('没有权限');
      throw new Error(res.msg || '没有权限');
    } else if (res.code === 401) {
      const token = getToken();
      if (token) {
        userLogout();
      }
      openLogin();
    } else if (res.code === 404) {
      message.warn(`当前版本不支持这个功能`);
    }

    requestList.value = requestList.value.filter(e => {
      return response.config.url !== e.path;
    });
    return response;
  },
  error => {
    const errMsg: string = error.toString();
    if (errMsg.includes('Network Error')) {
      message.warn('网络错误');
    } else if (errMsg.includes('canceled')) {
      // 用户取消请求
    } else {
      message.error(error.message);
    }
    return Promise.reject(error);
  },
);

/* 取消用户请求 */
export const cancelAllRequest = () => {
  requestList.value.forEach(e => {
    e.controller.abort('用户取消请求');
  });
  requestList.value = [];
};
